<template>
  <article class="innerPage adminList">
    <header class="breadcrumb">
      <x-breadcrumb :path="$route.path" :title="$route.meta.breadcrumb" :startIndex="$route.meta.startIndex">
      </x-breadcrumb>
    </header>
    <div class="search_pd">
      <searchCondition
        :formItemList="[]"
        :emitSearch="false"
        :resetSearch="true"
        @search="search"
        @reset="reset"
        ref="mychild"
      >
        <el-form-item label="添加时间">
          <el-date-picker
            clearable
            v-model="filterData.start_time"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="开始时间"
            style="width: 185px"
          >
          </el-date-picker>
          <span>~</span>
          <el-date-picker
            clearable
            v-model="filterData.end_time"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="结束时间"
            default-time="23:59:59"
            style="width: 185px"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input v-model="searchValue" placeholder="请输入"></el-input>
        </el-form-item>
      </searchCondition>
    </div>
    <section>
      <div class="decorate"></div>
      <div class="actionBar">
        <div class="btn_add">
          <el-button
            icon="el-icon-circle-plus-outline"
            class="btn-green icon-fontSize"
            @click="pageTurn('/systemSetting/adminList/add')"
            >添加</el-button
          >
        </div>
      </div>
      <div class="elTable">
        <el-table
          :border="$isborder"
          stripe
          ref="elTable"
          row-key="id"
          :data="resDetail.data"
          header-row-class-name="el-tableHeadClass"
          class="tableStyle"
          :header-cell-style="$headerCellStyle"
          size="mini"
        >
          <el-table-column
            fixed
            type="index"
            :index="indexMethod"
            label="序号" label-class-name="indexColumn"
            align="center"
            :width="$widtha"
            
            :header-cell-style="{
              background: '#d8d8d8',
              color: '#000000',
            }"
          >
          </el-table-column>
          <el-table-column prop="account" label="账号" :width="$widthb" align="left" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="username" label="姓名" :width="$widthb" align="left" show-overflow-tooltip>
            <template slot-scope="scope">
              <div style="padding: 5px 0">{{ scope.row.username }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="tel" label="电话" :width="$widthb" align="left" show-overflow-tooltip>
          </el-table-column>
          <!-- <el-table-column label="管辖位置" :width="$widthb" align="left" show-overflow-tooltip>
            <template slot-scope="{ row }">
              {{ row.way == 2 ? "图书馆" : row.way == 3 ? "书店" : "全部" }}
            </template>
          </el-table-column> -->
          <!-- <el-table-column
            label="管辖书店信息"
            :width="$widthc"
            align="left"
            show-overflow-tooltip
            v-if="wayData == 1"
          >
            <template slot-scope="{ row }">
              <span v-for="(item, index) in row.con_shop" :key="index">
                <span v-if="index !== 0">、</span>
                {{ item.shop_name }}
              </span>
            </template>
          </el-table-column> -->
          <el-table-column
            prop="role_name"
            label="管理员角色"
            :width="$widthb"
            align="left"
            show-overflow-tooltip
            v-if="wayData == 1"
          >
            <template slot-scope="scope">
              <el-tooltip placement="top">
                <div slot="content" style="width: 140px">
                  {{ scope.row.role_name }}
                </div>
                <p class="ellipsisText">{{ scope.row.role_name }}</p>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            prop="end_login_time"
            label="最后登录时间"
            :width="$widthb"
            align="left"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="create_time"
            label="添加时间"
            :min-width="$widthb"
            align="left"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right" :header-align="$heaerOpt">
            <template slot-scope="{ row }">
              <div class="btnFrom-box" v-if="account !== row.account">
                <div class="details-box" @click="tableActions(row, 'resetPassword')">修改密码</div>
                <div class="details-box" @click="tableActions(row, 'revise')"><span></span>修改</div>
                <div class="delete-box" @click="tableActions(row, 'delete')"><span></span> 删除</div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </section>
    <footer class="pagination">
      <div>
        <el-pagination
          background
          prev-text="上一页"
          next-text="下一页"
          layout="prev, pager, next, jumper"
          :total="resDetail.total"
          :page-size="filterData.limit"
          @current-change="selectPage"
          :current-page.sync="resDetail.current_page"
        >
        </el-pagination>
        
      </div>
      <p>
        共<span>{{ resDetail.total || 0 }}</span
        >数据
      </p>
    </footer>

    <!-- 对话框 -->
    <x-dialog
      :visible="dialogVisible"
      dangerBtnText="确认"
      infoBtnText="取消"
      @cancel="dialogVisible = false"
      @confirm="dialogConfirm"
    >
      <div class="dialogContent" v-if="dialogType === 'delete'">
        <x-svg-icon iconName="dialogCaution" className="iconClass"> </x-svg-icon>
        <p>{{ dialogContentText }}</p>
      </div>
      <div class="dialogContent" v-if="dialogType === 'resetPassword'">
        <x-svg-icon iconName="dialogCaution" className="iconClass"> </x-svg-icon>
        <p>{{ dialogContentText }}</p>
        <el-form ref="elForm" :model="formData" size="mini" :rules="rules">
          <el-form-item label="新密码" prop="password">
            <el-input
              type="password"
              clearable
              show-password
              placeholder="请输入新密码"
              autocomplete="off"
              v-model="formData.password"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirm_password">
            <el-input
              type="password"
              clearable
              show-password
              autocomplete="off"
              placeholder="请输入新密码"
              v-model="formData.confirm_password"
            >
            </el-input>
          </el-form-item>
        </el-form>
      </div>
    </x-dialog>
  </article>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      filterData: {
        keywords: "",
        start_time: "",
        end_time: "",
        page: 1,
        limit: 10,
      },
      resDetail: {
        data: [],
      },
      presentId: "",
      dialogType: "",
      dialogVisible: false,
      dialogContentText: "",

      formData: {
        password: "",
        confirm_password: "",
      },
      rules: {
        password: [
          {
            required: true,
            validator: this.$elValidator?.password,
            trigger: "blur",
          },
          {
            trigger: "blur",
            validator: (rule, value, callback) => {
              var passwordreg = /(?![A-Z]*$)(?![a-z]*$)(?![0-9]*$)(?![^a-zA-Z0-9]*$)/
              console.log(passwordreg.test(value))
              if (!passwordreg.test(value)) {
                callback(new Error("密码必须由字母和数字组成!"))
              } else {
                callback()
              }
            },
          },
        ],
        confirm_password: [
          {
            required: true,
            validator: this.validatorPassword2,
            trigger: "blur",
          },
        ],
      },
      wayData: undefined,
    }
  },
  created() {},
  activated() {
    let userInfo = localStorage.getItem("token")
    this.wayData = JSON.parse(userInfo).way
    if (this.$route.params.action == "refresh" || this.$isFirstInPage.get()) {
      this.resDetail = []
      this.filterData.start_time = ""
      this.filterData.end_time = ""
      this.filterData.keywords = ""
      this.filterData.page = 1
      this.api()
    }

    this.setPageTabs()
    this.$refs?.elTable?.doLayout()
  },
  computed: {
    account() {
      return JSON.parse(localStorage.getItem("token")).account
    },
  },
  methods: {
    //重置
    reset() {
      this.filterData.start_time = ""
      this.filterData.end_time = ""
      this.filterData.keywords = ""
      this.filterData.page = 1
      this.api()
    },
    //查询
    search() {
      let status = this.timeSlotValidator(this.filterData.start_time, this.filterData.end_time)
      if (status) {
      } else {
        return
      }
      this.filterData.page = 1
      this.api()
    },
    timeFormat(fn) {
      let status = this.timeSlotValidator(this.filterData.start_time, this.filterData.end_time)
      status && fn()
    },
    validatorPassword2(rule, v, callback) {
      let reg = /[\w_-]{6,20}/
      if (v) {
        if (reg.test(v)) {
          v + "" === this.formData.password + "" ? callback() : callback(new Error("两次输入密码不一致!"))
        } else {
          callback(new Error("密码为6到20位数之间"))
        }
      } else {
        callback(new Error("请输入新密码"))
      }
    },
    indexMethod(i) {
      return i + 1 + (this.resDetail.current_page - 1) * 10
    },
    resetList() {
      this.api()
    },
    // 获取数据
    async api() {
      try {
        let res = await this.request({
          url: "/admin/manage/list",
          method: "get",
          data: {
            ...this.filterData,
          },
        })
        this.resDetail = res.content
      } catch (err) {
        this.resDetail = { data: [], total: 0, current_page: 0, selectPage: 1 }
        this.errorHandler(err)
      }
    },
    tableActions(row, type) {
      if (type === "revise") {
        this.$router.push({
          path: "/systemSetting/adminList/revise",
          query: {
            id: row.id,
          },
        })
        return
      }
      this.presentId = row.id
      this.dialogType = type
      this.dialogVisible = true
      if (type === "delete") {
        this.dialogContentText = `确定删除账号：${row.account}？`
      } else if (type === "resetPassword") {
        this.formData = this.$options.data().formData
        this.dialogContentText = `修改密码，账号：${row.account}`
      }
    },

    dialogConfirm() {
      if (this.dialogType === "delete") {
        this.deleteItem()
      } else if (this.dialogType === "resetPassword") {
        this.resetPassword()
      }
    },
    async deleteItem() {
      try {
        const res = await this.request({
          url: "/admin/manage/del",
          method: "post",
          data: {
            id: this.presentId,
          },
        })
        this.dialogVisible = false
        this.$message({
          showClose: true,
          message: res.msg,
          type: "success",
        })
        setTimeout(() => {
          this.api()
        }, 1000)
      } catch (err) {
        this.dialogVisible = false
        this.errorHandler(err)
      }
    },
    async resetPassword() {
      await this.$refs?.elForm.validate()
      try {
        let res = await this.request({
          url: "/admin/manage/changePwd",
          method: "post",
          data: {
            id: this.presentId,
            ...this.formData,
          },
        })
        this.dialogVisible = false
        this.$message({
          showClose: true,
          message: res.msg || "修改成功",
          type: "success",
        })
      } catch (err) {
        this.errorHandler(err)
      }
    },
    selectPage(i) {
      this.filterData.page = i
      this.api()
    },
  },
  watch: {},
}
</script>

<style lang="scss" scoped>
@import "./style.scss";
</style>
